package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl  implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //1.查询前5天的文章数据
        Date date = DateTime.now().minusDays(50).toDate();
        List<ApArticle> articleList = apArticleMapper.findArticleListByLast5days(date);

        //2.计算文章的分值
        List<HotArticleVo> hotArticleVoList = computeHotArticle(articleList);

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);

    }

    @Autowired
    private IWemediaClient iWemediaClient;

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {

        ResponseResult resp = iWemediaClient.getChannels();

        if(resp.getCode().equals(200)){
            String jsonString = JSON.toJSONString(resp.getData());
            List<WmChannel> channelList = JSON.parseArray(jsonString, WmChannel.class);

            for (WmChannel wmChannel : channelList) {
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(wmChannel.getId()))
                        .sorted(Comparator.comparing(HotArticleVo::getScore,Comparator.reverseOrder()))
                        .collect(Collectors.toList());

                sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());


            }

        }

    }


    /**
     * 排序并且缓存数据
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        //上面已经排过顺序了
        //hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size() > 30) {
            hotArticleVos = hotArticleVos.subList(0, 30);
        }
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }


    private List<HotArticleVo> computeHotArticle(List<ApArticle> articleList) {

        ArrayList<HotArticleVo> hotArticleVos = new ArrayList<>();

        for (ApArticle apArticle : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            int score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            hotArticleVos.add(hotArticleVo);
        }

        return hotArticleVos;

    }

    /**
     * 计算分值
     * @param apArticle
     * @return
     */
    private int computeScore(ApArticle apArticle) {
        int score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
